package control

import (
	"encoding/json"
	"errors"
	"fmt"
	"gorm.io/gorm"
	"smmf/config"
	"smmf/model"
)

type UserPhoneReq struct {
	Phone    string `json:"phone" column:"phone"`
	PassWord string `json:"passWord" column:"passWord"`
}
type UserTokenRes struct {
	Token string `json:"token" column:"token"`
}
type UserPhoneRes struct {
	ID       int64  `json:"id" column:"ID"`
	Phone    string `json:"phone" column:"phone"`
	PassWord string `json:"passWord" column:"passWord"`
	Token    string `json:"token" column:"token"`
}
type User struct {
}

func (a *User) Register(data []byte, param Param, userId int64) (out interface{}, code int, err error) {
	req := UserPhoneReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		return nil, config.ERR_JSON, err
	}
	user, err := model.QueryUserId(req.Phone)

	if user.ID > 0 {
		return nil, config.ERR, errors.New("用户已存在")
	}

	if errors.Is(err, gorm.ErrRecordNotFound) {
		err = model.Register(req.Phone, req.PassWord)
		if err != nil {
			return nil, config.ERR, err
		}
		return nil, config.SUCCESS, nil
	}
	return nil, config.ERR, err
}

func (a *User) Login(data []byte, param Param, userId int64) (out interface{}, code int, err error) {
	req := UserPhoneReq{}
	err = json.Unmarshal(data, &req)
	if err != nil {
		return nil, config.ERR_JSON, err
	}
	user, err := model.QueryUserId(req.Phone)

	if err != nil {
		return nil, config.ERR, err
	}
	if user.Phone == req.Phone && user.PassWord == req.PassWord {
		res := &UserTokenRes{}

		token, err := GenerateToken(user.ID, user.Phone, user.PassWord)
		if err != nil {
			return nil, config.ERR, err
		}
		err = model.UpUserToken(user.ID, token)
		if err != nil {
			return nil, config.ERR, err
		}
		res.Token = token
		return res, config.SUCCESS, nil
	}
	return nil, config.ERR, errors.New("账号或者明码错误")
}

func (a *User) UserInfo(data []byte, param Param, userId int64) (out interface{}, code int, err error) {
	fmt.Println(userId)
	user, err := model.QueryUser(userId)
	if err != nil {
		return nil, config.ERR, err
	}
	return user, config.SUCCESS, nil
}
